package com.example.demo.controller;

import com.example.demo.entity.Project;
import com.example.demo.entity.ResponseInfo;
import com.example.demo.service.ProjectService;
import com.example.demo.utils.PageInfoNew;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/project")
@Api(tags = "项目管理")
public class ProjectController {
    @Resource
    ProjectService projectService;

    /**
     * project添加接口
     */
    @PostMapping("/add")
    @ApiOperation(value = "项目添加接口")
    public ResponseInfo<String> insertProject(@RequestBody Project project) {
        List<Project> projects = projectService.findByName(project.getProjectName());
        if (projects.size() > 0) {
            return ResponseInfo.errorInfo("项目名称:" + project.getProjectName() + "已存在");
        }
        projectService.insertProject(project);
        return ResponseInfo.successInfo("");
    }

    /**
     * 分页接口
     */
    @GetMapping("/page")
    @ApiOperation(value = "项目分页接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页数", required = true, dataType = "int"),
            @ApiImplicitParam(name = "pageSize", value = "每页长度", required = true, dataType = "int"),})
    public ResponseInfo<PageInfoNew<Project>> getProjectPage(@RequestParam int pageNum, @RequestParam int pageSize) {
        return ResponseInfo.successInfo(projectService.finAllWithPage(pageNum, pageSize));
    }

    /**
     * project编写接口
     */
    @PostMapping("/update")
    @ApiOperation(value = "项目更新接口")
    public ResponseInfo<String> updateProject(@RequestBody Project project) {
        if (project.getId() == 0) {
            return ResponseInfo.errorInfo("id不能为空");
        }
        projectService.updateProject(project);
        return ResponseInfo.successInfo("");
    }

    /**
     * project删除接口
     */
    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "项目删除接口")
    public ResponseInfo<String> deleteProject(@PathVariable("id") int projectId) {
        List<Project> projects = projectService.findById(projectId);
        if (projectId == 0) {
            return ResponseInfo.errorInfo("请输入id");
        } else if (projects.size() == 0) {
            return ResponseInfo.errorInfo("项目不存在");
        }
        projectService.deleteById(projectId);
        return ResponseInfo.successInfo("");
    }

    /**
     * 获取project所有的结果集
     */
    @GetMapping("/list")
    @ApiOperation(value = "获取所有项目接口")
    public ResponseInfo<List<Project>> getAllProject() {
        return ResponseInfo.successInfo(projectService.findAllProject());
    }
}
